package com.chenglu.android.mine.address;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.R;
import com.chenglu.android.common.base.BaseActivity;
import com.chenglu.android.common.base.BaseFullScreenActivity;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.StatusBarUtil;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.common.utils.Utils;
import com.chenglu.android.mine.address.adapter.AddressManagerAdapter;
import com.chenglu.android.mine.address.mvp.contract.AddressManagerContract;
import com.chenglu.android.mine.address.mvp.presenter.AddressManagerPresenter;
import com.chenglu.android.mine.bean.AddressListBean;
import com.chenglu.android.mine.bean.AddressSubmitBean;
import com.chenglu.android.mine.bean.AddressTreeBean;
import com.chenglu.android.mine.bean.CommonDataBean;
import com.chenglu.android.payment.ComfirmOrderActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: lyj
 * @Created: by Copyright 2023 3 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description：地址管理
 */
public class AddressManagerActivity extends BaseFullScreenActivity<AddressManagerPresenter> implements AddressManagerContract.View {

    public static final String ALLADDRESS = "ALLADDRESS";
    @BindView(R.id.rv_address_manager)
    RecyclerView rvAddressManager;
    @BindView(R.id.ll_loading_data)
    LinearLayout llLoadingData;
    @BindView(R.id.ll_loading_no_data)
    LinearLayout llLoadingNoData;
    @BindView(R.id.iv_no_data)
    ImageView ivNoData;
    @BindView(R.id.tv_no_data)
    TextView tvNoData;
    @BindView(R.id.btn_address)
    TextView btnAddress;
    @BindView(R.id.rl_btn_address)
    RelativeLayout rlBtnAddress;
    @BindView(R.id.ic_back)
    ImageView icBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;

    private AddressManagerAdapter amAdapter;

    List<AddressListBean.Data> list = new ArrayList<>();

    private String aaccessToken;

    //删除id
    private int deteleId;

    private boolean isAddressId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_manager);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        initView1();
    }


    protected void initView1() {
        //判断从哪里跳转
        isAddressId = getIntent().getBooleanExtra(ComfirmOrderActivity.ADDRESSID, false);


//        setCenterText("我的收货地址");
        tvTitle.setText("收货地址");
        mPresenter = new AddressManagerPresenter();
        mPresenter.attachView(this);
        //
        StatusBarUtil.immersive(this);
        StatusBarUtil.setPaddingSmart(this, toolbar);

//        SPUtils.setInt("addressId", 0);
        initCommentRv();
//        aaccessToken = SPUtils.getString("AaccessToken", "AaccessToken");
//        mPresenter.getAddressList(getToken());


    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (mPresenter == null) {
//            LogUtils.v("ddddd");
//        } else {
//
//            SPUtils.setInt("addressId", 0);
//            aaccessToken = SPUtils.getString("AaccessToken", "AaccessToken");
//            mPresenter.getAddressList(aaccessToken);
//        }
        list.clear();
        mPresenter.getAddressList(getToken());

    }


    private void initCommentRv() {
        amAdapter = new AddressManagerAdapter(mContext, R.layout.item_address_manager, list);
        rvAddressManager.setLayoutManager(new LinearLayoutManager(mContext));
        rvAddressManager.setAdapter(amAdapter);

        amAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_address_edit:
                        Intent intent = new Intent(mContext, AddressEditActivity.class);
                        AddressListBean.Data data = amAdapter.getData().get(position);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(AddressEditActivity.ADDRESSDATA, data);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                    case R.id.tv_address_delete:

                        deteleId = position;
                        //请求删除接口
                        if (amAdapter.getData().get(position).getId() != null) {

                            //去保存的时候 检查地址和所在地区变化和改变
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("id", amAdapter.getData().get(position).getId());

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }

                        break;


                }
            }
        });

        amAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (isAddressId) {
//                    SPUtils.setInt("addressId", amAdapter.getData().get(position).getId());

//                    String consignee = amAdapter.getData().get(position).getConsignee();
//                    String mobile = amAdapter.getData().get(position).getMobile();
//
//                    String province = amAdapter.getData().get(position).getProvince();
//                    String city = amAdapter.getData().get(position).getCity();
//                    String district = amAdapter.getData().get(position).getDistrict();
//                    String address = amAdapter.getData().get(position).getAddress();
//                    SPUtils.setString(ALLADDRESS, "收货地址：" + consignee + " " + mobile + province + city + district + address);
                    Intent intent = new Intent();
                    intent.putExtra("ADDRESS_DATA", amAdapter.getData().get(position).getId());
                    // 设置返回码和返回携带的数据
                    setResult(Activity.RESULT_OK, intent);
                    // RESULT_OK就是一个默认值，=-1，它说OK就OK吧
                    finish();

                }

            }
        });
//        commentAdapter.notifyDataSetChanged();
    }

    //记住本来的id
    int id = 0;

    @Override
    public void getAddressList(AddressListBean addressList) {

        LogUtils.d("Jinlai----");
        if (addressList.getData().size() > 0) {
            LogUtils.d("Jinlai");
            list.clear();
            llLoadingData.setVisibility(View.VISIBLE);
            llLoadingNoData.setVisibility(View.GONE);
            for (int i = 0; i < addressList.getData().size(); i++) {
                list.add(addressList.getData().get(i));

            }
            amAdapter.notifyDataSetChanged();
        } else {
            llLoadingNoData.setVisibility(View.VISIBLE);
            llLoadingData.setVisibility(View.GONE);
        }

    }


    public static List removeDuplicate(List<AddressListBean.Data> list) {
        List<AddressListBean.Data> listTemp = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            if (!listTemp.contains(list.get(i).getId())) {
                listTemp.add(list.get(i));
            }
        }
        return listTemp;

    }

    @Override
    public void getAddressSubmit(AddressSubmitBean bean) {

    }

    @Override
    public void getAddressUpdate(AddressSubmitBean submitBean) {

    }

    @Override
    public void getAddressTree(AddressTreeBean treeBean) {

    }

    /**
     * @description 删除id数据集合
     */

    @Override
    public void getAddressDelete(CommonDataBean deleteBean) {

        list.remove(deteleId);
        amAdapter.setNewData(list);
        amAdapter.notifyDataSetChanged();
        ToastUtils.show("删除成功");
        if (list.size() < 1) {
            llLoadingNoData.setVisibility(View.VISIBLE);
            llLoadingData.setVisibility(View.GONE);
        }
    }

    @Override
    public void onError(String errorMsg) {
        isLogin = false;
        SPUtils.setBoolean("ISLOGIN", false);
        showXPopupView(mContext, "提示", "登录已过期,请重新登录", "登录");
    }


    @OnClick({R.id.rl_btn_address, R.id.ic_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_btn_address:
                Intent intent = new Intent(mContext, AddressEditActivity.class);
                mContext.startActivity(intent);
                //右侧跳转动画
//                ((BaseActivity) mContext).overridePendingTransition(R.anim.slide_in_from_right,R.anim.slide_out_from_left);

                break;
            case R.id.ic_back:
                finish();
                break;
        }
    }



}
